﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Backend_Category_Default : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		this.Form.Action = "Backend/Category/Default.aspx";
		if (!IsPostBack)
		{
			GetCategory();
		}
	}

	// Get all categories
	protected void GetCategory()
	{
		CategoryList.DataSource = EF_Category.GetCategory();
		CategoryList.DataBind();
	}

	// Enable editable row
	protected void CategoryList_RowEditing(object sender, GridViewEditEventArgs e)
	{
		CategoryList.EditIndex = e.NewEditIndex;
		GetCategory();
	}
	protected void CategoryList_RowDeleting(object sender, GridViewDeleteEventArgs e)
	{
		string categoryId = this.CategoryList.Rows[e.RowIndex].Cells[1].Text;
		if (EF_Category.DeleteCategory(categoryId))
		{
			displayMessage.Text = "ប្រភេទម្ហូបត្រូវបានលុប!";
			displayMessage.CssClass = "alert-success";
		}
		else
		{
			displayMessage.Text = "មិនអាចលុបមុខម្ហូបនេះបានទេ!";
			displayMessage.CssClass = "alert-danger";
		}
		GetCategory();
	}
	protected void CategoryList_RowUpdating(object sender, GridViewUpdateEventArgs e)
	{
		EF_CategoryProperty category = new EF_CategoryProperty();
		GridViewRow gvRow = this.CategoryList.Rows[e.RowIndex];
		category.CategoryID = Int32.Parse(CategoryList.Rows[e.RowIndex].Cells[1].Text);
		category.Name = ((TextBox)gvRow.Cells[2].Controls[0]).Text;
		category.Description = ((TextBox)gvRow.Cells[3].Controls[0]).Text;
		category.Status = bool.Parse(((TextBox)gvRow.Cells[5].Controls[0]).Text);
		if (EF_Category.UpdateCategory(category))
		{
			displayMessage.Text = category.Name + " ត្រូវបានកែប្រែ!";
			displayMessage.CssClass = "alert-success";
			CategoryList.EditIndex = -1;
		}
		else
		{
			displayMessage.Text = "មិនអាចធ្វើការកែប្រែ " + category.Name + " បានទេ!";
			displayMessage.CssClass = "alert-danger";
		}
		GetCategory();
	}

	// Cancel editing
	protected void CategoryList_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
	{
		CategoryList.EditIndex = -1;
		GetCategory();
	}
}